package com.xiaoyu.studyworkspace.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xiaoyu.studyworkspace.common.kapaentity.register.appbooting.AppBooting;
import com.xiaoyu.studyworkspace.common.kapaentity.register.login.UserLogin;
import com.xiaoyu.studyworkspace.common.kapaentity.userinfo.RootBean;
import com.xiaoyu.studyworkspace.common.kapaentity.userinfo.User_info;
import com.xiaoyu.studyworkspace.common.kapaentity.websocket.*;
import com.xiaoyu.studyworkspace.common.util.*;
import com.xiaoyu.studyworkspace.common.websocketclient.*;
import com.xiaoyu.studyworkspace.dto.AutoConfigDTO;
import com.xiaoyu.studyworkspace.dto.AutoUserDTO;
import com.xiaoyu.studyworkspace.dto.ChangRoomDTO;
import com.xiaoyu.studyworkspace.dto.SecretDTO;
import com.xiaoyu.studyworkspace.mapper.AutoPlayMapper;
import com.xiaoyu.studyworkspace.pojo.AutoConfig;
import com.xiaoyu.studyworkspace.pojo.AutoLog;
import com.xiaoyu.studyworkspace.pojo.AutoUser;
import com.xiaoyu.studyworkspace.service.AutoPlayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class AutoPlayServiceImpl implements AutoPlayService {

    @Autowired
    private AutoPlayMapper autoPlayMapper;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public AutoUser userLoginAutoPlay(SecretDTO secretDTO) {
        if (StrUtil.isEmpty(secretDTO.getSecret())) {
            return null;
        }
        String[] split = secretDTO.getSecret().split("@");
        if (split.length != 3) {
            log.info("分割错误--{}", Arrays.toString(split));
            return null;
        }
        HashMap<String, Object> paramMap = new HashMap<>();
        //查询数据库是否存在该用户
        AutoUser isAutoUser = autoPlayMapper.selectUserInfoById(Long.parseLong(split[0]));
        if (isAutoUser != null && split[2].equals(isAutoUser.getPassword())) {
            //检测init和session
            paramMap.put(KapaParam.CODE, KapaCode.SELECT_ORDER);
            paramMap.put(KapaParam.DATA, "%7B%22type%22%3A1%2C%22page%22%3A1%2C%22limit%22%3A1000%7D");
            paramMap.put(KapaParam.DEPLOY_APP_ID, KapaCode.DEPLOY_APP_ID);
            paramMap.put(KapaParam.INIT_ID, isAutoUser.getInit_id());
            paramMap.put(KapaParam.SESSION_ID, isAutoUser.getSession_id());
            String post = HttpUtil.post(KapaCode.URL, KapaHttpUtil.convertParam(paramMap));
            RootBean rootBean = JSONUtil.toBean(post, RootBean.class);
            if (rootBean.getCode() == 0) {
                //说明有效
                return isAutoUser;
            }
        }
        AutoUser autoUser = new AutoUser();
        AppBooting appBooting = KapaHttpUtil.getAppBooting();
        if (appBooting == null) {
            log.info("ip池异常");
            throw new RuntimeException("ip池异常");
        }
        //发起登录
        paramMap.put(KapaParam.CODE, KapaCode.LOGIN);
        paramMap.put(KapaParam.DEPLOY_APP_ID, KapaCode.DEPLOY_APP_ID);
        paramMap.put(KapaParam.INIT_ID, appBooting.getInit_id());
        paramMap.put(KapaParam.SESSION_ID, appBooting.getSession_id());
        UserLogin userLogin = new UserLogin();
        userLogin.setMobile(split[1]);
        String passwordMd5 = DigestUtils.md5DigestAsHex(("login_password_" + split[2]).getBytes());
        userLogin.setLogin_password(passwordMd5);
        paramMap.put(KapaParam.DATA, URLEncoder.encode(JSONUtil.toJsonStr(userLogin)));
        String userLoginResponse = HttpUtil.post(KapaCode.URL, KapaHttpUtil.convertParam(paramMap));
        RootBean rootBean2 = JSONUtil.toBean(userLoginResponse, RootBean.class);
        if (rootBean2.getCode() != 0) {
            //不为0出现异常
            log.info("{}登录异常：{}", split[0], userLoginResponse);
            return null;
        }
        paramMap.put(KapaParam.DATA, KapaCode.DEVICE_INFO);
        paramMap.put(KapaParam.CODE, KapaCode.BIND);
        HttpUtil.post(KapaCode.URL, KapaHttpUtil.convertParam(paramMap));
        //调用接口，返回用户的数据
        paramMap.put(KapaParam.CODE, KapaCode.GET_INFO);
        paramMap.put(KapaParam.DATA, "%7B%7D");
        paramMap.put(KapaParam.DEPLOY_APP_ID, KapaCode.DEPLOY_APP_ID);
        paramMap.put(KapaParam.INIT_ID, appBooting.getInit_id());
        paramMap.put(KapaParam.SESSION_ID, appBooting.getSession_id());
        String kapaResponse = HttpUtil.post(KapaCode.URL, KapaHttpUtil.convertParam(paramMap));
        RootBean rootBean = JSONUtil.toBean(kapaResponse, RootBean.class);
        User_info user_info = rootBean.getData().getUser_info();
        BeanUtils.copyProperties(user_info, autoUser);
        autoUser.setPassword(split[2]);
        autoUser.setInit_id(appBooting.getInit_id());
        autoUser.setSession_id(appBooting.getSession_id());
        autoUser.setCreate_time(LocalDateTime.now());

        if (isAutoUser != null) {
            //更新数据
            autoUser.setIs_auto(isAutoUser.getIs_auto());
            autoPlayMapper.updateAutoUser(autoUser);
        }
        if (isAutoUser == null) {
            autoUser.setIs_auto(0);
            //写入数据库中
            autoPlayMapper.insertUserInfo(autoUser);
        }
        //数据库查询所有的自动用户
        List<AutoUser> autoUsers = autoPlayMapper.selectAllAutoUsers();
        //写入缓存当中
        redisTemplate.opsForValue().set("autoUsers", autoUsers);
        redisTemplate.expire("autoUsers", 5, TimeUnit.MINUTES);
        return autoUser;
    }

    @Override
    public AutoConfig getAutoConfigByID(int userId) {
        AutoConfig autoConfig = autoPlayMapper.selectAutoConfigById(userId);
        return autoConfig;
    }

    @Override
    public List<AutoLog> getAutoLogsById(AutoUserDTO autoUserDTO) {
        //先从缓存中读取
        List<AutoLog> autoLogs = (List<AutoLog>) redisTemplate.opsForValue().get("auto_logs" + autoUserDTO.getUser_id());
        if (autoLogs == null) {
            autoLogs = autoPlayMapper.selectAutoLogsBySize(autoUserDTO.getUser_id(), 100);
        }
        return autoLogs;
    }

    @Override
    public void updateAutoConfig(AutoConfigDTO autoConfigDTO) {

        AutoConfig autoConfig = new AutoConfig();
        BeanUtils.copyProperties(autoConfigDTO, autoConfig);
        autoConfig.setCreate_time(LocalDateTime.now());
        autoConfig.setIs_skip_betting(autoConfigDTO.getIs_skip_betting() ? 1 : 0);
        autoConfig.setIs_skip_number(autoConfigDTO.getIs_skip_number() ? 1 : 0);

        AutoConfig autoConfig1 = autoPlayMapper.selectAutoConfigById(autoConfigDTO.getUser_id());
        if (autoConfig1 == null) {
            //插入一条配置
            autoPlayMapper.insertAutoConfigById(autoConfig);
        }
        //不为空则更新配置
        autoPlayMapper.updateAutoConfig(autoConfig);
    }

    @Override
    public void startAutoBetting(AutoUserDTO autoUserDTO) {
        AutoUser autoUser = new AutoUser();
        autoUser.setUser_id(autoUserDTO.getUser_id());
        autoUser.setIs_auto(autoUserDTO.getIs_auto());
        log.info(autoUserDTO.toString());
        autoPlayMapper.updateAutoUserIsAuto(autoUser);
    }

    @Override
    public void insertDefaultAutoConfig(AutoUser autoUser) {
        //查询有无默认的auto_config
        AutoConfig autoConfig1 = autoPlayMapper.selectAutoConfigById(autoUser.getUser_id());
        if (autoConfig1 == null) {
            AutoConfig autoConfig = new AutoConfig();
            autoConfig.setPrediction_name("AI预测法");
            autoConfig.setUser_id(autoUser.getUser_id());
            autoConfig.setSize(1);
            autoConfig.setProfit(300.0);
            autoConfig.setLose(100.0);
            autoConfig.setMultiple(5);
            autoConfig.setWincount_stop(50);

            autoConfig.setIs_skip_betting(0);
            autoConfig.setSkip_betting(1);

            autoConfig.setIs_skip_number(0);
            autoConfig.setSkip_number(1);

            autoConfig.setContinue_fail(10);
            autoConfig.setMultiple_reset(3);
            autoConfig.setContinue_fail_skip(0);
            autoConfig.setCreate_time(LocalDateTime.now());
            autoPlayMapper.insertAutoConfigById(autoConfig);
        }
    }

    @Override
    public String changRoom(ChangRoomDTO changRoomDTO) {
        String currentId = BaseContext.getCurrentId();
        KapaSocketClient kapaSocketClient = KapaSocketClient.KAPA_SOCKET_CLIENT_MAP.get(Integer.valueOf(currentId));
        if (kapaSocketClient == null) {
            return "尚未开启挂机";
        }
        //房间名字获取id
        KapaChangeRoom kapaChangeRoom = new KapaChangeRoom();
        KapaSocket kapaSocket = new KapaSocket();
        kapaSocket.setCmdCode(1);
        kapaSocket.setCmdMerge(KapaCmdMerge.CHANGE_ROOM);
        String nextRoomName = changRoomDTO.getRoomName();
        Integer nextRoomId = KapaRoomID.roomByID.get(nextRoomName);
        kapaChangeRoom.setNextRoomId(nextRoomId);
        kapaSocketClient.setPrevent(nextRoomId);
        kapaChangeRoom.setPrevRoomId(kapaSocketClient.getPrevent());
        kapaSocket.setData(JSONUtil.toJsonStr(kapaChangeRoom).getBytes());
        //获取对应的client
        kapaSocketClient.send(kapaSocket.toString().getBytes(StandardCharsets.UTF_8));
        kapaSocketClient.getAutoLog().setPrediction(nextRoomName);
        return "跳至" + nextRoomName;
    }
}
